<template>
  <div>
    <div v-if="falg3">
      <div class="basic">
        <el-card>
          <div class="tip">
            <span style="color:#F56C6C">*</span>套餐外部显示图片配置
          </div>
          <el-upload action="https://api.xstarlife.com/systemapp/upload/singleFileUpload" list-type="picture-card" :limit="1" :headers="{ uploadScene: 'avatar' }" :on-success="iconImgUpSuccess" :on-remove="iconImgRemove" :file-list="goodsAttachForm.iconImgList" :on-exceed="upLimit">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-card>

        <el-card style="margin-top: 10px">
          <div class="tip">
            <span style="color:#F56C6C">*</span>套餐详情头部图片配置
          </div>
          <el-upload action="https://api.xstarlife.com/systemapp/upload/singleFileUpload" list-type="picture-card" :limit="6" :headers="{ uploadScene: 'avatar' }" :on-success="headImgUpSuccess" :on-remove="headImgRemove" :before-upload="beforeUpload" :file-list="goodsAttachForm.headImgList">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-card>
        <el-card style="margin-top: 10px">
          <div class="tip">
            <span style="color:#F56C6C">*</span>套餐详情图片配置
          </div>
          <el-upload action="https://api.xstarlife.com/systemapp/upload/singleFileUpload" list-type="picture-card" :headers="{ uploadScene: 'avatar' }" :on-success="detailImgUpSuccess" :on-remove="detailImgRemove" :before-upload="beforeUpload" :file-list="goodsAttachForm.detailImgList">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-card>
        <!-- 套餐不需要规格图片配置 -->
        <!-- <el-card>
          <div class="tip">
            <span style="color:#F56C6C">*</span>规格图片配置
          </div>
          <el-upload
            action="https://api.xstarlife.com/systemapp/upload/singleFileUpload"
            list-type="picture-card"
            :limit="1"
            :headers="{ uploadScene: 'avatar' }"
            :on-success="guigeImgUpSuccess"
            :on-remove="guigeImgRemove"
            :file-list="goodsAttachForm.guigeImgList"
            :on-exceed="upLimit"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-card> -->

        <el-card style="margin-top: 10px">
          <div class="tip">
            <span style="color:#F56C6C">*</span>套餐清单配置
          </div>
          <el-button style="background-color:#fd804c;color: #fff;margin-bottom:8px;" @click="addArea">新增区域</el-button>
          <el-table :data="tableData" border :span-method="objectSpanMethod">
            <el-table-column prop="areaName" label="区域/其他" min-width="12%">
              <template slot-scope="scope">
                <el-input v-model="scope.row.areaName" placeholder="输入名称" size="mini" />
              </template>
            </el-table-column>
            <el-table-column prop="areaTitle" label="标题" min-width="28%">
              <template slot-scope="scope">
                <el-input v-model="scope.row.areaTitle" placeholder="请输入标题名称" maxlength="15" show-word-limit size="mini" />
              </template>
            </el-table-column>
            <el-table-column prop="areaDescription" label="描述" min-width="40%">
              <template slot-scope="scope">
                <el-input v-model="scope.row.areaDescription" placeholder="请输入服务描述" maxlength="40" show-word-limit size="mini" />
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="20%">
              <template slot-scope="scope">
                <el-button size="mini" @click="handleAddSameArea(scope.$index, scope.row)">新增</el-button>
                <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
      <div class="buttons">
        <el-button style="background-color:#fd804c;color: #fff;margin-top: 10px" @click="Cancel">取消</el-button>
        <el-button style="background-color:#fd804c;color: #fff;margin-top: 10px" @click="Prew">上一步</el-button>
        <el-button style="background-color:#fd804c;color: #fff;margin-top: 10px" @click="Save">保存</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import Bus from "../../../api/bus";
export default {
  props: {
    goodsPackageAttaches: {
      type: Array,
      required: true
    },
    goodsPackageInventories: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      introduce: "",
      falg3: false,
      tableData: [
        {
          areaName: "",
          areaTitle: "",
          areaDescription: ""
        }
      ],
      goodsAttachForm: {
        iconImgList: [],
        headImgList: [],
        detailImgList: [],
        guigeImgList: []
      }
    };
  },
  activated () {
    Bus.$on("falg3", data => {
      //取  Bus.$on
      this.falg3 = data;
    });
    this.merage();
  },
  methods: {
    Cancel () {
      this.$router.push("/PackageListLi");
    },
    Prew () {
      this.falg3 = false;
      Bus.$emit("falg2", true);
    },
    async Save () {
      // 当前页面校验
      const flag = this.validate();
      if (!flag) return;
      // 图片接口
      debugger;
      const arr1 = this.returnPicturesObj(this.goodsAttachForm.iconImgList, 1);
      const arr2 = this.returnPicturesObj(this.goodsAttachForm.headImgList, 2);
      const arr3 = this.returnPicturesObj(
        this.goodsAttachForm.detailImgList,
        3
      );
      const arr4 = this.returnPicturesObj(this.goodsAttachForm.guigeImgList, 4);
      const goodsPackageAttaches = [...arr1, ...arr2, ...arr3, ...arr4];
      const data = {
        goodsPackageCode: this.$route.query.goodsPackageCode,
        goodsPackageAttaches
      };
      await this.$http({
        url: "/hssgoodsadmin/serviceGoodsPkg/updateGoodsPackageAttach",
        method: "POST",
        data
      });
      // 清单接口
      const data1 = {
        goodsPackageCode: this.$route.query.goodsPackageCode,
        goodsPackageInventories: this.tableData
      };
      await this.$http({
        url: "/hssgoodsadmin/serviceGoodsPkg/updateGoodsPackageInventory",
        method: "POST",
        data: data1
      });
      // this.$message.success('当前页面数据保存成功')
      // this.$emit('research')
      this.$router.push("/PackageListLi");
    },
    validate () {
      let flag = true;
      if (this.goodsAttachForm.iconImgList.length === 0) {
        this.$message.error("请配置套餐外部显示图片");
        flag = false;
        return false;
      }
      if (this.goodsAttachForm.headImgList.length === 0) {
        this.$message.error("请配置套餐详情头部显示图片");
        flag = false;
        return false;
      }
      if (this.goodsAttachForm.detailImgList.length == 0) {
        this.$message.error("请配置套餐详情显示图片");
        flag = false;
        return false;
      }
      // if (this.goodsAttachForm.guigeImgList.length == 0) {
      //   this.$message.error('请配置规格显示图片')
      //   flag = false
      //   return false
      // }
      if (this.tableData.length == 0) {
        this.$message.error("请填写套餐清单配置");
        flag = false;
        return false;
      }
      this.tableData.forEach(item => {
        if (
          item.areaName == "" ||
          item.areaTitle == "" ||
          item.areaDescription == ""
        ) {
          this.$message.error("请填写完整套餐清单配置");
          flag = false;
          return false;
        }
      });
      return flag;
    },
    beforeUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    upLimit (files, fileList) {
      this.$message.error("套餐外部图片只能上传一张，请先删除再上传");
    },
    iconImgUpSuccess (res, file, fileList) {
      this.goodsAttachForm.iconImgList.push(file);
    },
    iconImgRemove () {
      this.goodsAttachForm.iconImgList = [];
    },
    headImgUpSuccess (res, file, fileList) {
      this.goodsAttachForm.headImgList.push(file);
    },
    headImgRemove (file, fileList) {
      this.goodsAttachForm.headImgList = fileList;
    },
    detailImgUpSuccess (res, file, fileList) {
      this.goodsAttachForm.detailImgList.push(file);
    },
    detailImgRemove (file, fileList) {
      this.goodsAttachForm.detailImgList = fileList;
    },
    guigeImgUpSuccess (res, file, fileList) {
      this.goodsAttachForm.guigeImgList.push(file);
    },
    guigeImgRemove () {
      this.goodsAttachForm.guigeImgList = [];
    },
    addArea () {
      // 非空判断
      let flag = false;
      this.tableData.forEach(item => {
        if (
          item.areaName == "" ||
          item.areaTitle == "" ||
          item.areaDescription == ""
        ) {
          this.$message.error("请先填写完整");
          flag = true;
        }
      });
      if (flag) return;
      this.tableData.push({
        areaName: "",
        areaTitle: "",
        areaDescription: ""
      });
    },
    handleDelete (index, row) {
      if (index == 0) {
        this.$message.error("清单为必填项");
        return false;
      }
      this.tableData.splice(index, 1);
    },
    handleAddSameArea (index, row) {
      if (!row.areaName) {
        this.$message.error("请先填写当前行的区域");
        return false;
      }
      this.tableData.splice(index + 1, 0, {
        areaName: row.areaName,
        areaTitle: "",
        areaDescription: ""
      });
    },
    merageInit () {
      this.NameArr = [];
      this.NamePos = 0;
    },
    merage () {
      this.merageInit();
      for (let i = 0; i < this.tableData.length; i += 1) {
        if (i === 0) {
          // 第一行必须存在
          this.NameArr.push(1);
          this.NamePos = 0;
        } else {
          if (this.tableData[i].areaName === this.tableData[i - 1].areaName) {
            this.NameArr[this.NamePos] += 1;
            this.NameArr.push(0);
          } else {
            this.NameArr.push(1);
            this.NamePos = i;
          }
        }
      }
    },
    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        // 第一列的合并方法
        const row1 = this.NameArr[rowIndex];
        const col1 = row1 > 0 ? 1 : 0;
        return {
          rowspan: row1,
          colspan: col1
        };
      }
    },
    // 解决图片抖动的字段处理
    returnPicturesObj (arr, key) {
      const newArr = [];
      arr.forEach(item => {
        if (item.hasOwnProperty("response")) {
          // element上传的字段
          newArr.push({
            attachPosition: key,
            attachType: 1,
            attachUrl: item.response.data,
            coverUrl: ""
          });
        } else {
          // 原有上传的字段
          newArr.push({
            attachPosition: key,
            attachType: 1,
            attachUrl: item.attachUrl,
            coverUrl: ""
          });
        }
      });
      return newArr;
    }
  },
  mounted () {
    this.merage();
  },
  watch: {
    tableData: {
      handler (newvalue) {
        if (newvalue.length >= 2) {
          this.merage();
        }
      },
      deep: true
    },
    goodsPackageAttaches (newvalue) {
      if (newvalue) {
        // 外部图片
        this.goodsAttachForm.iconImgList = newvalue.filter(item => {
          return item.attachPosition == 1;
        });
        this.goodsAttachForm.iconImgList.forEach(item => {
          item.url = item.attachUrl;
        });
        // 详情头图
        this.goodsAttachForm.headImgList = newvalue.filter(item => {
          return item.attachPosition == 2;
        });
        this.goodsAttachForm.headImgList.forEach(item => {
          item.url = item.attachUrl;
        });
        // 详情图片
        this.goodsAttachForm.detailImgList = newvalue.filter(item => {
          return item.attachPosition == 3;
        });
        this.goodsAttachForm.detailImgList.forEach(item => {
          item.url = item.attachUrl;
        });
        // 规格图片
        this.goodsAttachForm.guigeImgList = newvalue.filter(item => {
          return item.attachPosition == 4;
        });
        this.goodsAttachForm.guigeImgList.forEach(item => {
          item.url = item.attachUrl;
        });
      }
    },
    goodsPackageInventories (newvalue) {
      if (newvalue) {
        this.tableData = newvalue;
      }
    }
  }
};
</script>
<style scoped>
.basic {
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;
  position: relative;
}
.Useful {
  font-size: 18px;
  margin-bottom: 15px;
}
.tip {
  padding: 8px 16px;
  background-color: #ecf8ff;
  border-radius: 4px;
  border-left: 5px solid #50bfff;
  margin: 20px 0;
  font-size: 16px;
}
.buttons {
  text-align: center;
  position: absolute;
  bottom: -70px;
  left: 50%;
  transform: translateX(-50%);
}
</style>
<style lang="scss" scoped>
// /deep/ .el-upload-list__item.is-ready {
//   display: none;
// }
</style>
